<?php
/**
 * Created by PhpStorm.
 * User: 吕金鹏
 * Date: 2021/5/21
 * Time: 9:05 上午
 */

namespace app\index\controller;


use think\Db;
use think\facade\Request;

class Power extends Base
{
    // 查看角色
    public function role()
    {
        $data = selectData('role');
        $data = getTrees($data);
        $this->assign('data',$data);
        return $this->fetch('role');
    }

    // 新增角色
    public function addRole()
    {
        if (Request::isPost()){
            $data = input('post.');
            foreach ($data['rule'] as $k => $v){
                $rule[] = Db::name('menu')->where('id',$v)->field('pid')->find();
            }

            foreach ($rule as $k => $v){
                $newRule[] = Db::name('menu')->where('id',$v['pid'])->field('pid')->find();
            };
            $newRule = array_merge($rule,$newRule);
            foreach ($newRule as $k => $v){
                $zong[] = strval($v['pid']);
            }

            $data['rule'] = array_merge($data['rule'],array_unique($zong));
            $data['rule'] = json_encode($data['rule']);

            insertData('role',$data);
        }
        $where['pid'] = 0;
        $menu = selectData('menu',$where);
        foreach ($menu as $k => $v){
            $where1['pid'] = $v['id'];
            $menu[$k]['item'] = selectData('menu',$where1);

            foreach ($menu[$k]['item'] as $i => $j){
                $where2['pid'] = $j['id'];
                $menu[$k]['item'][$i]['item'] = selectData('menu',$where2);
            }
        }

        $data = getTrees(selectData('role'));
        $this->assign('data',$data);
        $this->assign('menu',$menu);
        return $this->fetch('addRole');
    }

    // 修改角色
    public function editRole()
    {
        if (Request::isPost()){
            $data = input('post.');

            foreach ($data['rule'] as $k => $v){
                $rule[] = Db::name('menu')->where('id',$v)->field('pid')->find();
            }

            foreach ($rule as $k => $v){
                $newRule[] = Db::name('menu')->where('id',$v['pid'])->field('pid')->find();
            };
            $newRule = array_merge($rule,$newRule);
            foreach ($newRule as $k => $v){
                $zong[] = strval($v['pid']);
            }

            $data['rule'] = array_merge($data['rule'],array_unique($zong));
            $data['rule'] = json_encode($data['rule']);

            $where['id'] = $data['id'];
            $res = upDate('role',$where,$data);
            if ($res) ajaxMsg(1,'修改成功');
            ajaxMsg(0,'网络不佳,修改失败');
        }
        $id = input('id');
        $where['id'] = $id;
        $data = findData('role',$where);
        $mid = json_decode($data['rule'],true);
        $role = getTrees(selectData('role'));
        $where1['pid'] = 0;
        $menu = selectData('menu',$where1);
        foreach ($menu as $k => $v){
            $where2['pid'] = $v['id'];
            $menu[$k]['item'] = selectData('menu',$where2);

            foreach ($menu[$k]['item'] as $i => $j){
                $where3['pid'] = $j['id'];
                $menu[$k]['item'][$i]['item'] = selectData('menu',$where3);
                foreach($menu[$k]['item'][$i]['item'] as $l => $m){
                    if(in_array($menu[$k]['item'][$i]['item'][$l]['id'],$mid))$menu[$k]['item'][$i]['item'][$l]['ck'] = 'checked';
                    else $menu[$k]['item'][$i]['item'][$l]['ck'] = '';
                }
            }
        }
        // echo 123;die;
        $this->assign('id',$id);
        $this->assign('menu',$menu);
        $this->assign('mid',$mid);
        $this->assign('role',$role);
        $this->assign('data',$data);
        return $this->fetch('editRole');
    }

    // 删除角色
    public function delRole()
    {
        $id = input('id');
        $where['pid'] = $id;
        if (findData('role',$where)) ajaxMsg(0,'该角色有下级角色,请先清空下级角色再删除此角色');
        
        $where1['id'] = $id;
        $res = delData('role',$where1); ajaxMsg(1,'删除成功');
        ajaxMsg(0,'删除失败,请稍后再试');
    }

    // 管理员列表
    public function admin()
    {
        $table = ['admin as a','role as r'];
        $name = input('name');
        $rid = input('rid');
        $where = [];
        if($rid){
            $where['a.rid'] = $rid;
        }
       $where1[] = ['a.id','not in','733,732,731'];
        
        if($this->admin['lv']==3){
            if ($name){
                $adminList = Db::name('admin a')
                ->leftjoin('role r','a.rid = r.id')
                // ->leftjoin('cate c',)
                ->whereLike('a.name',$name.'%')
                ->where('a.school',$this->admin['school'])
                ->where('rid',12)
                ->where($where)
                ->where($where1)
                ->order('a.time desc')
                ->field('a.*,r.title')
                ->paginate(10,false,['query'=>request()->param()]);
            }else{
                $where = 'a.rid='.'r.id';
                $adminList = Db::name('admin a')
                    ->join('role r','a.rid = r.id')
                    ->where('a.school',$this->admin['school'])
                    ->where('rid',12)
                    ->where($where)
                    ->where($where1)
                    ->order('a.time desc')
                    ->field('a.*,r.title')
                    ->paginate(10,false,['query'=>request()->param()]);
            }
        }elseif($this->admin['lv']==2){
            if ($name){
                $adminList = Db::name('admin a')
                ->leftjoin('role r','a.rid = r.id')
                ->whereLike('a.name',$name.'%')
                ->where('a.area',$this->admin['area'])
                ->where('rid','in',[12,8])
                ->where($where)
                ->where($where1)
                ->order('a.time desc')
                ->field('a.*,r.title')
                ->paginate(10,false,['query'=>request()->param()]);
            }else{
                $where = 'a.rid='.'r.id';
                $adminList  = Db::name('admin a')
                    ->join('role r','a.rid = r.id')
                    ->where('a.area',$this->admin['area'])
                    ->where('rid','in',[12,8])
                    ->where($where)
                    ->where($where1)
                    ->order('a.time desc')
                    ->field('a.*,r.title')
                    ->paginate(10,false,['query'=>request()->param()]);
            }
        }else{
            $cate = input('cate');
            $ids = '';
            if($cate){
                
                $id_ary = Db::name('cate')->where("pid",$cate)->select(); 
                foreach($id_ary as $key=>$val){
                        if($key==0){
                            $ids .= $val['id'];
                        }else{
                            $ids .=','.$val['id'];
                        }
                }
                if($cate==68){
                   
                    $id_ary = Db::name('cate')->where("pid",'in',$ids)->select(); 
                    $ids ='';
                    foreach($id_ary as $key=>$val){
                        if($key==0){
                            $ids .= $val['id'];
                        }else{
                            $ids .=','.$val['id'];
                        }
                    }
                }
                // $where['school']= array('in',$ids);
                // $where['lv'] = 3;
            }
            if ($name){
               
                if($ids){
                     $adminList = Db::name('admin a')
                    ->leftjoin('role r','a.rid = r.id')
                    ->whereLike('a.name',$name.'%')
                    ->where($where)
                    ->where($where1)
                    ->order('a.time desc')
                    ->where("school",'in',$ids)
                    ->where('a.lv','=',3)
                    ->field('a.*,r.title')
                    ->paginate(10,false,['query'=>request()->param()])
                    ->each(function($item){
                        if($itme['rid']==9){
                            $item['count'] = Db::name('shenqing')->where('school_id',$item['school'])->count();
                        }else{
                            $item['count'] = '不统计';
                        }
                        
                        return $item;
                    });
                }else{
                     $adminList = Db::name('admin a')
                    ->leftjoin('role r','a.rid = r.id')
                    ->whereLike('a.name',$name.'%')
                    ->where($where)
                    ->where($where1)
                    ->order('a.time desc')
                    // ->where('a.lv','<',2)
                    ->field('a.*,r.title')
                    ->paginate(10,false,['query'=>request()->param()])
                    ->each(function($item){
                        if($item['rid']==8){
                             $item['count'] = Db::name('shenqing')->where('school_id',$item['school'])->count();
                        }else{
                            $item['count'] = '不统计';
                        }
                       
                        return $item;
                    });
                }
            }else{
                // echo $ids;die;
                if($ids){
                    $adminList = Db::name('admin a')
                    ->join('role r','a.rid = r.id')
                    ->where($where)
                    ->where("school",'in',$ids)
                    ->where('a.lv','=',3)
                    ->order('a.time desc')
                    ->field('a.*,r.title')
                    ->paginate(10,false,['query'=>request()->param()])
                    ->each(function($item){
                        if($itme['rid']==9){
                            $item['count'] = Db::name('shenqing')->where('school_id',$item['school'])->count();
                        }else{
                            $item['count'] = '不统计';
                        }
                        
                        return $item;
                    });
                    // echo Db::name('admin')->getlastsql();die;
                }else{
                    if($rid==9){
                        
                        $adminList = Db::name('admin a')
                        ->join('role r','a.rid = r.id')
                        ->where($where)
                        ->where($where1)
                        ->order('a.time desc')
                        ->field('a.*,r.title')
                        ->paginate(10,false,['query'=>request()->param()])
                        ->each(function($item){
                            $id_ary = Db::name("cate")->where('pid',$item['area'])->select();
                            
                            $area_ids = '';
                            foreach($id_ary as $key=>$val){
                                if($key==0){
                                    $area_ids.=$val['id'];
                                }else{
                                    $area_ids.=','.$val['id'];
                                }
                            }
                            if($item['rid']==9){
                                 $item['count'] = Db::name('shenqing')->where('school_id','in',$area_ids)->count();
                            }else{
                                $item['count']  = '不统计';
                            }
                           
                            return $item;
                        });
                    }else{
                        $adminList = Db::name('admin a')
                        ->join('role r','a.rid = r.id')
                        ->where($where)
                        ->where($where1)
                        ->order('a.time desc')
                        ->field('a.*,r.title')
                        ->paginate(10,false,['query'=>request()->param()])
                        ->each(function($item){
                            if($item['rid']==8){
                                 $item['count'] = Db::name('shenqing')->where('school_id',$item['school'])->count();
                            }else{
                                $item['count']  = '不统计';
                            }
                           
                            return $item;
                        });
                    }
                    
                }
            }
        }
        $ary = $adminList->toarray();
        foreach($ary['data'] as &$val){
            if($val['lv']==3){
                $val['mange_title'] = Db::name('cate')->where('id',$val['school'])->find()['title'];
            }elseif($val['lv']==2){
                $val['mange_title'] = Db::name('cate')->where('id',$val['area'])->find()['title'];
            }else{
                $val['mange_title'] = '';
            }
        }
        // dump($ary);die;
        $this->assign('admin_data',$this->admin);
        $this->assign('admin',$ary['data']);
        $this->assign('page',$adminList->render());
        return $this->fetch('admin');
    }

    // 添加管理员
    public function addAdmin()
    {
        if (Request::isPost()){
            $data = input('post.');
            // dump($data);die;
            if (strlen($data['password'])<6) ajaxMsg(0,'密码长度最小6位');
            $where['phone'] = $data['phone'];
            if (findData('admin',$where)) ajaxMsg(0,'该号码已注册');
            $data['time'] = time();
            $data['password'] = sha1($data['password']);
            if(!isset($data['lv'])&&$this->admin['lv']!=2&&$this->admin['lv']!=3){
                $data['lv']=1;
            }
            
            if($this->admin['lv']==3){
                $data['school'] =$this->admin['school'];
            }elseif($this->admin['lv']==2){
                $data['area'] =$this->admin['area'];
                $data['school'] = $data['cid'];
            }elseif($this->admin['lv']==0&&$data['rid']==12){
                $data['cid'] = 0;
            }else{
                if($data['rid']==8){
                    $data['school'] = $data['cid'];
                    $data['area'] = Db::name("cate")->where("id",$data['cid'])->find()['pid'];
                }elseif($data['rid']==9||$data['lv']==68){
                    $data['area'] = $data['cid'];
                    $data['lv'] = 2;
                }
            }
            $data['idcard'] = 'SH'.$data['idcard'];
            if($data['rid']==12){
                $data['idcard'] = 'ZJ'.$data['idcard'];
            }

            insertData('admin',$data);

        }
        
        if($this->admin['lv']==2){
            $data=Db::name("role")->where("id",'in','8')->select();
        }elseif($this->admin['id']==1){
            $data=Db::name("role")->select();
        }else{
            $data=Db::name("role")->where("id",'in','11,8,9')->select();
        }
        // dump($this->admin);die;
        $this->assign('admin',$this->admin);
        $data = getTrees($data);
        $this->assign('data',$data);
        return $this->fetch('addAdmin');
    }
    public function zhuanjia(){
        if($this->admin['lv']==3){
            // $data['school'] =$this->admin['school'];
            $list = Db::name('admin')->where('school',$this->admin['school'])->where('rid',12)->paginate(10,false,['query'=>request()->param()]);
            
        }elseif($this->admin['lv']==2){
            $list = Db::name('admin')->where('area',$this->admin['area'])->where('rid',12)->paginate(10,false,['query'=>request()->param()]);
        }else{
            // echo 123;die;
             $list = Db::name('admin')->where('cid',0)->where('rid',12)->paginate(10,false,['query'=>request()->param()]);
        }
        $this->assign('admin',$list);
        $this->assign('admin_data',$this->admin);
        $this->assign('page',$list->render());
        return $this->fetch();
    }
    public function addzhuanjia(){
        if (Request::isPost()){
            $data = input('post.');
            if(isset($data['bz'])){
                $res = Db::name('admin')->where('id',$this->admin['id'])->update(['bz'=>$data['bz']]);
                if($res){
                    $res = Db::name('admin')->where('id',$this->admin['id'])->find();
                    Cookie('admin',json_encode($res));
                    ajaxMsg(1,'添加成功');
                }
                ajaxmsg('0','网络错误');
            }
            // dump($data);die;
            if (strlen($data['password'])<6) ajaxMsg(0,'密码长度最小6位');
            $where['phone'] = $data['phone'];
            if (findData('admin',$where)) ajaxMsg(0,'该号码已注册');
            $data['time'] = time();
            $data['password'] = sha1($data['password']);
            if(!isset($data['lv'])&&$this->admin['lv']!=2&&$this->admin['lv']!=3){
                $data['lv']=1;
            }
            
            if($this->admin['lv']==3){
                $data['school'] =$this->admin['school'];
            }elseif($this->admin['lv']==2){
                $data['area'] =$this->admin['area'];
                // $data['school'] = $data['cid'];
            }elseif($this->admin['rid']==11&&$data['rid']==12){
                $data['cid'] = 0;
            }else{
                if($data['lv']==3){
                    $data['school'] = $data['cid'];
                    $data['area'] = Db::name("cate")->where("id",$data['cid'])->find()['pid'];
                }elseif($data['lv']==2||$data['lv']==68){
                    $data['area'] = $data['cid'];
                    $data['lv'] = 2;
                }
            }
            $data['idcard'] = 'ZJ'.$data['idcard'];
            insertData('admin',$data);

        }
        $admin = Db::name('admin')->where('id',$this->admin['id'])->find();
        // dump($admin);die;
        if($admin['bz']==''){
            
            echo "<script>location.href='/index/power/uploadzj'</script>";die;
        }
        if($this->admin['lv']==2){
            $data=Db::name("role")->where("id",'in','8')->select();
        }else{
            $data=Db::name("role")->where("id",'in','11,8,9')->select();
        }
        // dump($this->admin);die;
        $this->assign('admin',$this->admin);
        $data = getTrees($data);
        $this->assign('data',$data);
        return $this->fetch();
    }
    
    // 量表授权
    public function powerBiao()
    {
        if (Request::isPost()){
            $data = input('post.');
            $data['bid'] = json_encode($data['bid']);
            if (findData('biao_power','aid='.$data['aid'])){
                $res = upDate('biao_power','id='.$data['aid'],$data);
                if ($res) ajaxMsg(1,'授权更新成功');
                ajaxMsg(0,'授权更新失败');
            }
            insertData('biao_power',$data);
        }
        $id = input('id');
        $power = findData('biao_power','aid='.$id);
        $newPower = json_decode($power['bid'],true);
        $biao = selectData('biao');
        foreach ($biao as $key => $value){
            if ($newPower){
                if (in_array($value['id'],$newPower)) $biao[$key]['ck'] = true;
                else $biao[$key]['ck'] = false;
            }else{
                $biao[$key]['ck'] = false;
            }

        }
        $this->assign('id',$id);
        $this->assign('biao',$biao);
        $this->assign('power',$power);
        return $this->fetch('powerBiao');
    }

    // 修改管理员
    public function editAdmin()
    {
        if (Request::isPost()){
            $data = input('post.');
            // if (strlen($data['password'])<6) ajaxMsg(0,'密码长度最小6位');
            if(!isset($data['password'])||$data['password']==''){
                unset($data['password']);
            }else{
                $data['password'] = sha1($data['password']);
            }
            
            $where='idcard ="'.$data['idcard'].'" and id !='.$data['id'];
            // echo $where;die;
            if (findData('admin',$where)) ajaxMsg(0,'该号码已注册');
            $data['time'] = time();
          

            $res = upDate('admin','id='.input('id'),$data);
            if ($res) ajaxMsg(1,'修改成功');
            ajaxMsg(0,'修改失败,请稍后再试');
        }
        $id = input('id');

        $admin = findData('admin','id='.$id);
        if($this->admin['lv']==3){
            $data=Db::name("role")->where("id",'in','12')->select();
        }else{
            $data=Db::name("role")->where("id",'in','11,8,9')->select();
        }
        // dump($data);die;
        if($admin['lv']==2){
            $bumen = Db::name('cate')->where('id',$admin['area'])->find()['title'];
        }elseif($admin['lv']==3){
            $bumen = Db::name('cate')->where('id',$admin['school'])->find()['title'];
        }else{
            $bumen='';
        }
        $this->assign('bumen',$bumen);
        $this->assign('data',$data);
        $this->assign('admin',$admin);
        return $this->fetch('editAdmin');
    }

    // 删除管理员账号
    public function delAdmin()
    {
        $id = input('id');
        $this_admin = Db::name('admin')->where('id',$id)->find();
        // dump($this_admin);
        if($this_admin['rid']==12){
            $if_dafen = Db::name("dafen")->where('admin_id',$this_admin['id'])->select();
            if($if_dafen){
                ajaxMsg(0,'专家已有评分记录,请勿删除！');
            }
        }
        // dump($if_dafen);die;
        if (delData('admin','id='.$id)) ajaxMsg(1,'删除成功');
        ajaxMsg(0,'删除失败,请稍后再试');
    }
    //绑定分组
    public function getgroup(){
        $lv = input('lv');
        if($lv == 68){
            $list = Db::name("cate")->where('pid',68)->select();
        }elseif($this->admin['lv']==2){
            $list = Db::name("cate")->where('pid',$this->admin['area'])->select();
        }else{
            $list = Db::name("cate")->where('lv',$lv)->select();
        }
        ajaxMsg(1,$list);
    }
    //上传专家评分标准
    public function uploadzj(){
        // $info = Db::name()->where()->find();
        $file = request()->file('file');
        if($file){
            $res = Upload($file,[],'/uploads/field/');
            if($res){
                Db::name('admin')->where('id',$this->admin['id'])->update(['bz'=>$res['filePath']]);
            }
    //        filePath
            ajaxMsg(1,'上传成功');
        }
        $admin = Db::name('admin')->where('id',$this->admin['id'])->find();
        
        $this->assign('admin',$admin);
        return $this->fetch();
    }





}